import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 前端给后端传参(前后端交互)的三种方式：
// 1> getParameter获取get的query string，2> getParameter获取form表单post请求的body的键值对
// 3> getInputStream获取post请求的json格式的body，还可以使用jackson来把键值对的值封装到Java对象中
@WebServlet("/getParameter")
public class GetParameterServlet extends HttpServlet {
    // 获取query string
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 路径：/getParameter?user=lisi&age=20
        String user = req.getParameter("user");
        String age = req.getParameter("age");

        resp.setContentType("text/html; charset=utf-8");
        resp.getWriter().write("user:"+user+" age:"+age);
    }

    //获取post请求的body键值对
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 路径：/getParameter
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        resp.setContentType("text/html; charset=utf-8");
        resp.getWriter().write("username:"+username+" password:"+password);
    }
}
